#!/bin/bash

# 1. 构建项目
echo "开始构建项目..."
npm run build

# 2. 构建Docker镜像
echo "构建Docker镜像..."
docker build -t chat-wise .

# 3. 启动Redis
echo "启动Redis服务..."
docker run -d \
    --name redis-server \
    -p 6379:6379 \
    redis:latest

# 4. 启动应用实例
echo "启动应用实例..."
docker run -d \
    --name chat-wise-1 \
    -p 3000:3000 \
    -e NODE_ENV=production \
    -e REDIS_HOST=redis-server \
    --link redis-server \
    chat-wise

docker run -d \
    --name chat-wise-2 \
    -p 3001:3000 \
    -e NODE_ENV=production \
    -e REDIS_HOST=redis-server \
    --link redis-server \
    chat-wise

# 5. 配置Nginx
echo "配置Nginx..."
cat > /etc/nginx/conf.d/chat-wise.conf << EOF
upstream nextjs_upstream {
    server 127.0.0.1:3000;
    server 127.0.0.1:3001;
    keepalive 64;
}

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://nextjs_upstream;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_cache_bypass \$http_upgrade;
    }
}
EOF

# 6. 重启Nginx
echo "重启Nginx..."
nginx -s reload

# 7. 设置监控
echo "配置监控..."
# 安装Prometheus Node Exporter
docker run -d \
    --name node-exporter \
    -p 9100:9100 \
    prom/node-exporter

# 8. 配置日志收集
echo "配置日志收集..."
# 启动ELK Stack
docker run -d \
    --name elasticsearch \
    -p 9200:9200 \
    -p 9300:9300 \
    -e "discovery.type=single-node" \
    elasticsearch:7.9.3

docker run -d \
    --name logstash \
    --link elasticsearch:elasticsearch \
    logstash:7.9.3

docker run -d \
    --name kibana \
    --link elasticsearch:elasticsearch \
    -p 5601:5601 \
    kibana:7.9.3

echo "部署完成！"
echo "请访问 http://example.com 查看应用"
echo "请访问 http://localhost:5601 查看Kibana监控面板"